﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WxReader.Properties;

namespace WxReader
{
    public partial class FormWxReader : Form
    {
        public const string WXREADER_URL = "https://weread.qq.com/";
        public string ZoomConfPath { get; } = System.IO.Path.GetTempPath() + "\\wx-reader-zoom";
        public FormWxReader()
        {
            InitializeComponent();
            this.webViewWxReader.Source = new Uri(WXREADER_URL);
            this.webViewWxReader.ContentLoading += WebView21_ContentLoading;
            InitZoom();
        }

        private void InitZoom()
        {
            this.webViewWxReader.ZoomFactorChanged += (object sender, EventArgs e) =>
            {
                var zoom = this.webViewWxReader.ZoomFactor;
                // 保存缩放
                var path = System.IO.Path.GetTempPath() + "\\wx-reader-zoom";
                try
                {
                    File.WriteAllText(path, zoom.ToString());
                }
                catch (Exception) { }
                this.Text = $"微信读书({zoom*100}%)";
            };
            if (File.Exists(ZoomConfPath))
            {
                string zoomConf = string.Empty;
                try
                {
                    zoomConf = File.ReadAllText(ZoomConfPath);
                }
                catch (Exception) { }
                if (double.TryParse(zoomConf, out double zoom) && zoom > 0)
                {
                    this.webViewWxReader.ZoomFactor = zoom;
                }
            }
            this.Text = $"微信读书({this.webViewWxReader.ZoomFactor * 100}%)";
        }

        private void WebView21_ContentLoading(object sender, Microsoft.Web.WebView2.Core.CoreWebView2ContentLoadingEventArgs e)
        {
            var text = $@"
                var s = document.createElement('style')
                s.innerHTML = `{GetCssResource()}`;
                document.head.appendChild(s)
                ";
            webViewWxReader.CoreWebView2.ExecuteScriptAsync(text);
        }

        private string GetCssResource()
        {
            return Resources.wxreader;
        }
    }
}
